<template>
    <!-- 对话框表单 -->
    <el-dialog
        custom-class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="baTable.form.operate ? true : false"
        :destroy-on-close="true"
        @close="baTable.toggleForm"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    label-position="right"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <FormItem
                        :label="t('station.station_name')"
                        type="string"
                        v-model="baTable.form.items!.station_name"
                        prop="station_name"
                        :input-attr="{ placeholder: t('Please input field', { field: t('station.station_name') }) }"
                    />
                    <FormItem
                        :label="t('station.image')"
                        type="image"
                        v-model="baTable.form.items!.image"
                        prop="image"
                        :input-attr="{ placeholder: t('Please select field', { field: t('station.image') }) }"
                    />
                    <FormItem
                        :label="t('station.business')"
                        type="string"
                        v-model="baTable.form.items!.business"
                        prop="business"
                        :input-attr="{ placeholder: t('Please input field', { field: t('station.business') }) }"
                    />
                    <FormItem
                        :label="t('station.old_price')"
                        type="number"
                        prop="old_price"
                        v-model.number="baTable.form.items!.old_price"
                        :input-attr="{ step: '0.01', placeholder: t('Please input field', { field: t('station.old_price') }) }"
                    />
                    <FormItem
                        :label="t('station.price')"
                        type="number"
                        prop="price"
                        v-model.number="baTable.form.items!.price"
                        :input-attr="{ step: '0.01', placeholder: t('Please input field', { field: t('station.price') }) }"
                    />
                    <FormItem
                        :label="t('station.oil_array')"
                        type="array"
                        v-model="baTable.form.items!.oil_array"
                        prop="oil_array"
                        :input-attr="{ placeholder: t('Please input field', { field: t('station.oil_array') }) }"
                        customkey="油号,例如柴油,92,95,98"
                        customvalue="枪号,多个以英文逗号“,”隔开"
                    />
                    <FormItem
                        :label="t('station.lat')"
                        type="string"
                        v-model="baTable.form.items!.lat"
                        prop="lat"
                        :input-attr="{ placeholder: t('Please input field', { field: t('station.lat') }) }"
                    />
                    <FormItem
                        :label="t('station.lng')"
                        type="string"
                        v-model="baTable.form.items!.lng"
                        prop="lng"
                        :input-attr="{ placeholder: t('Please input field', { field: t('station.lng') }) }"
                    />
                    <el-form-item label="地址">
                        <el-input v-model="baTable.form.items!.address"></el-input>
                        <el-button style="margin-top: 10px" @click="changeLatlng">搜索</el-button>
                    </el-form-item>
                    <div id="container"></div>
                    <div style="clear: both"></div>
                    <FormItem
                        :label="t('category.switch')"
                        type="switch"
                        v-model="baTable.form.items!.switch"
                        prop="switch"
                        :input-attr="{ placeholder: t('Please input field', { field: t('category.switch') }) }"
                    />
                    <FormItem
                        :label="t('station.weight')"
                        type="number"
                        prop="weight"
                        v-model.number="baTable.form.items!.weight"
                        :input-attr="{ step: '1', placeholder: t('Please input field', { field: t('station.weight') }) }"
                    />
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm('')">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, inject, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type baTableClass from '/@/utils/baTable'
import FormItem from '/@/components/formItem/index.vue'
import type { ElForm, FormItemRule } from 'element-plus'
import { ElNotification } from 'element-plus'
import { buildValidatorData } from '/@/utils/validate'
window._AMapSecurityConfig = {
    securityJsCode: '12ead795431b9cfb8b6611f3533bca0e',
}
import AMapLoader from '@amap/amap-jsapi-loader'

let map = {
    add: {},
}
let isShowMap = false
let amap = {}
function initMap() {
    AMapLoader.load({
        key: '662bf24c17a4ef09bd334d7c51b95c3f', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.PlaceSearch'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
        .then((AMap: any) => {
            amap = AMap
            map = new AMap.Map('container', {
                //设置地图容器id
                viewMode: '2D', //是否为3D地图模式
                zoom: 5, //初始化地图级别
                // center: [116.33775883619342, 39.99289495144838], //初始化地图中心点位置
            })

            map.on('click', function (e: any) {
                console.log(e)
                baTable.form.items!.lat = e.lnglat.getLat()
                baTable.form.items!.lng = e.lnglat.getLng()
            })
            if (baTable.form.items!.lat && baTable.form.items!.lng) {
                map.setCenter([baTable.form.items!.lng, baTable.form.items!.lat])
                map.setZoom(18)
                addMarker(baTable.form.items!.lng, baTable.form.items!.lat)
            }
        })
        .catch((e: any) => {
            console.log(e)
        })
}

function test() {
    console.log(23)
}

function addMarker(lng: any, lat: any) {
    let marker = new amap.Marker({
        // icon: "https:////a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        position: [lng, lat],
        // offset: new amap.Pixel(-13, -30)
    })
    marker.setMap(map)
}

function changeLatlng() {
    amap.plugin('AMap.PlaceSearch', function () {
        var autoOptions = {
            city: '全国',
        }
        var placeSearch = new amap.PlaceSearch(autoOptions)
        placeSearch.search(baTable.form.items!.address, function (status, result) {
            // 搜索成功时，result即是对应的匹配数据
            console.log(result)
            if (result.info == 'OK' && result.poiList && result.poiList.pois[0]) {
                let data = result.poiList.pois[0]
                console.log(data)
                map.setCenter([data.location.lng, data.location.lat])
                map.setZoom(18)
                addMarker(data.location.lng, data.location.lat)
                baTable.form.items!.lat = data.location.lat
                baTable.form.items!.lng = data.location.lng
            } else {
                ElNotification({
                    type: 'error',
                    message: '没搜索到任何内容',
                })
            }
        })
    })
}

const formRef = ref<InstanceType<typeof ElForm>>()
const baTable = inject('baTable') as baTableClass

const { t } = useI18n()

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    station_name: [buildValidatorData('required', t('station.station_name'))],
    image: [buildValidatorData('required', t('station.image'))],
    address: [buildValidatorData('required', t('station.address'))],
    business: [buildValidatorData('required', t('station.business'))],
    old_price: [buildValidatorData('required', t('station.old_price'))],
    price: [buildValidatorData('required', t('station.price'))],
    lat: [buildValidatorData('required', t('station.lat'))],
    lng: [buildValidatorData('required', t('station.lng'))],
    oil_array: [buildValidatorData('required', t('station.oil_array'))],
    switch: [buildValidatorData('required', t('station.switch'))],
    weight: [buildValidatorData('required', t('station.weight'))],
})

watch(
    () => baTable.form.loading,
    (newVal) => {
        if (!newVal) {
            initMap()
        }
    }
)
watch(
    () => baTable.form.operate,
    (newVal) => {
        if (newVal == 'add') {
            initMap()
        }
    }
)
</script>

<style scoped lang="scss">
#container {
    padding: 0px;
    width: 80%;
    height: 300px;
    margin: 0 auto;
    float: right;
    background: #fff;
}
.ba-table-form-scrollbar {
    position: relative;
}
</style>
